package com.ruoyi.common.wecom.handlers;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;

@Slf4j
public class DefaultWeComResponseHandler<T> extends AbstractWeComResponseHandler<T> {

    private Class<T> type;

    public DefaultWeComResponseHandler(Class<T> type) {
        this.type = type;
    }

    @Override
    public T handleResponse(HttpResponse response) throws IOException {
        log.info("DefaultWeComResponseHandler::handleResponse start, param:" + response);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        if (statusLine.getStatusCode() >= 300) {
            EntityUtils.consume(entity);
            throw new HttpResponseException(statusLine.getStatusCode(),
                statusLine.getReasonPhrase());
        }
        if (entity == null) {
            return null;
        }
        String responseStr =  EntityUtils.toString(entity, Charset.forName("utf-8"));
        log.info("企业微信返回信息：" + responseStr);
        log.info("DefaultWeComResponseHandler::handleResponse end, return:" + responseStr);
        return getResponse(responseStr);
    }

    @Override
    protected T getResponse(String responseStr) {
        T responseObject = JSON.parseObject(responseStr, type);
        return responseObject;
    }

}
